import React, { Component } from 'react'
import './index.less'
import { withRouter } from 'react-router-dom'
import { Row, Col, Table, Button, Card, Modal, message, Select } from 'antd'
import WeeklyForm from './weeklyForm'
import moment from 'moment'
import Http from '../../../../axios'
const Option = Select.Option;

class PersonalWeekly extends Component {

  state = {
    editFlag: false,
    createFlag: false,
    userInfo: '',
    date: '',
    workday: 5,
    modalVisible: false,
    weeklyData: [],
    index: 1,
    timeUsed: 0,
    record: '',
    modifyRecord: '',
    weeklyDataArray: [],
    deletedReportDetailIds: [],
    projectInfo: [],
    projectCode: '',
    reportCode: ''
  }

  componentWillMount() {
    const userId = this.props.location.state && this.props.location.state.userId;
    const userInfo = JSON.parse(window.localStorage.getItem('userInfo'));
    this.setState({
      userInfo: userInfo,
      date: this.getWeek()
    })
    if (userId === userInfo.id) {
      this.setState({
        editFlag: true,
      })
    }
    this.getweeklyDataArray();
    this.getProjectInfo();
  }

  getweeklyDataArray = () => {
    Http.request({
      url: '/individual_report/search',
      params: {
        value: this.props.location.state && this.props.location.state.username
      }
    }).then((resData) => {
      this.setState({
        weeklyDataArray: resData.data
      })
    })
  }

  getProjectInfo = () => {
    Http.request({
      url: '/projectInfo/query/all'
    }).then((resData) => {
      this.setState({
        projectInfo: resData.data
      })
    })
  }
  
  getWeek = () => {
    let str = new Date();
    let week = Math.ceil(str.getDate()/7);
    let month = str.getMonth() + 1;
    let year = str.getFullYear();
    if  (str.getDate() < 7) {
        if (str.getDay() !== 1) {
            week = 5;
            month = str.getMonth();
        }
    }
    return {year, month, week}
  }

  goBack = () => {
    this.props.history.goBack();
  }

  create = () => {
    this.setState({
      createFlag: true,
      record: '',
      reportCode: '',
      weeklyData: [],
      workday: 5
    })
  }
  createBack = () => {
    this.setState({
      createFlag: false,
    })
  }

  addData = () => {
    this.setState({
      modalVisible: true,
      modifyRecord: ''
    })
    if (this.state.weeklyData.length > 0) {
      this.setState({
        index: this.state.weeklyData[this.state.weeklyData.length - 1].index + 1
      })
    }
  }
  viewWeekly = (record, index) => {
    this.setState({
      reportCode: record.reportCode
    })
    Http.request({
      url: `/individual_report_detail/list/${record.reportCode}`
    }).then((resData) => {
      let weeklyData = resData.data.data;
      for (let i = 0; i < weeklyData.length; i++) {
        weeklyData[i].index = i + 1;
      }
      this.setState({
        createFlag: true,
        record: resData.data,
        weeklyData,
        workday: resData.data.validDay
      })
    })
  }

  closeModal = () => {
    this.setState({
      modalVisible: false
    })
  }
  submitData = (data) => {
    data.key = data.index;
    data.projectCode = this.state.projectCode
    let weeklyData = this.state.weeklyData;
    if (this.state.modifyRecord === '') {
      weeklyData.push(data);
    } else {
      weeklyData.splice(parseInt(data.key, 10) - 1, 1, data)
    }
    
    let totalTime = 0;
    for (let item of weeklyData) {
      totalTime += parseInt(item.workHour, 10)
    }
    this.setState({
      modalVisible: false,
      weeklyData,
      timeUsed: totalTime
    })
  }

  // workdayChange = (event) => {
  //   this.setState({
  //     workday: event.target.value
  //   })
  // }
  workdayChange = (data) => {
    this.setState({
      workday: data
    })
  }

  submit = () => {
    let postData = {};
    postData.validDay = this.state.workday;
    postData.data = this.state.weeklyData;
    for (let item of postData.data) {
      item.expectDate = moment(item.expectDate).format('YYYY-MM-DD');
    }
    postData.deletedReportDetailIds = this.state.deletedReportDetailIds;
    let url;
    if (this.state.reportCode === '') {
      url = '/individual_report/add'
    } else {
      url = `/individual_report/update/${this.state.reportCode}`;
    }
    Http.request({
      url: url,
      method: 'post',
      data: postData
    }).then((resData) => {
      message.success('提交成功');
      this.getweeklyDataArray();
      this.createBack();
    })
  }

  modifyItem = (modifyRecord) => {
    modifyRecord.expectDate = moment(new Date(modifyRecord.expectDate).getTime());
    this.setState({
      modifyRecord,
      modalVisible: true
    })
  }

  deleteItem = (deleteRecord) => {
    let deleteID = this.state.deletedReportDetailIds;
    deleteID.push(deleteRecord.code);
    this.setState({
      deletedReportDetailIds: deleteID
    })
    this.state.weeklyData.splice(deleteRecord.index - 1, 1);
    let array = this.state.weeklyData;
    for (let index in array) {
      array[index].index = parseInt(index, 10) + 1;
      array[index].key = parseInt(index, 10) + 1;
    }
    this.setState({
      weeklyData: array
    })
  }

  setProjectCode = (code) => {
    this.setState({
      projectCode: code
    })
  }

  render() {
    const columns = [{
      title: '责任人',
      dataIndex: 'username',
      key: 'username',
    },  
    {
      title: '周报期数',
      dataIndex: 'date',
      key: 'date',
    }, 
    {
      title: '填写时间',
      dataIndex: 'createTime',
      key: 'createTime',
    }];
    const columns2 = [
      {
        title: '序号',
        dataIndex: 'index',
        key: 'index',
      },
      {
        title: '项目名称',
        dataIndex: 'projectName',
        key: 'projectName',
      },
      {
        title: '项目类别',
        dataIndex: 'projectType',
        key: 'projectType',
      },
      {
        title: '项目编号',
        dataIndex: 'projectNo',
        key: 'projectNo',
      },
      {
        title: '任务简述',
        dataIndex: 'taskDesc',
        key: 'taskDesc',
      },
      {
        title: '当前进展(%)',
        dataIndex: 'progressType',
        key: 'progressType',
      },
      {
        title: '本周投入时间(小时)',
        dataIndex: 'workHour',
        key: 'workHour',
      },
      {
        title: '预期完成时间',
        dataIndex: 'expectDate',
        key: 'expectDate',
        render: (text, record) => moment(record.expectDate).format('YYYY-MM-DD')
      },
      {
        title: '是否延期',
        dataIndex: 'delay',
        key: 'delay',
        render: (text, record) => {
          switch (record.delay) {
            case true:
              return '是'
            default:
              return '否'
          }
        }
      },
      {
        title: '问题和风险',
        dataIndex: 'risk',
        key: 'risk',
      },
      {
        title: '操作',
        dataIndex: 'operation',
        key: 'operation',
        render: (text, record) => (
          <span className={this.state.editFlag ? '' : "react-show"}>
            <a onClick={() => this.modifyItem(record)}>修改</a>
            <span className="ant-divider" />
            <a onClick={() => this.deleteItem(record)}>删除</a>
          </span> 
        )
      },
    ]
    return (
      <section className="base-section">
        <div className={this.state.createFlag ? 'react-show' : ''}>
          <Row className="top-row">
            <Col span={19}>
              <Button className={this.state.editFlag ? 'create-button' : "create-button react-show"} type="primary" onClick={this.create}>写周报</Button>
              <Button className="create-button" type="primary" onClick={this.goBack}>返回</Button>
            </Col>
            <Col span={5} type="flex" justify="center">
              {/* <Search placeholder="请输入搜索内容" className="search" onSearch={value => console.log(value)}/> */}
            </Col>
          </Row>
          <Row>
            <Table columns={columns} dataSource={this.state.weeklyDataArray.list} onRowClick={this.viewWeekly} 
            pagination={{defaultPageSize: 10, total: this.state.weeklyDataArray.count , showSizeChanger: true}} />
          </Row>
        </div>
        <div className={!this.state.createFlag ? 'react-show' : ''}>
          <Card title={`${this.state.date.year}年${this.state.date.month}月第${this.state.date.week}周`} bordered={false}>
            <Row className="form-row">
              <Col className="form-col" span={8}>
                <span className="lable">责任人：</span>
                <span>{this.state.editFlag ? this.state.userInfo.username : this.state.record.username}</span>
              </Col> 
              <Col className="form-col" span={8}>
                <span className="lable">责任人部门：</span>
                <span>{this.state.editFlag ? this.state.userInfo.departName : this.state.record.departmentName}</span>
              </Col>
              <Col className="form-col" span={8}>
                <span className="lable">有效工作时长：</span>
                {
                  !this.state.editFlag ? <span>{this.state.record.validDay}</span> :
                  // <Input className="lable2" addonAfter="天" onChange={this.workdayChange} defaultValue={this.state.workday} 
                  // type="number" step={0.1} min={0.1} max={5} />
                  <Select allowClear value={this.state.workday} onChange={this.workdayChange}>
                    <Option value={1}>1</Option>
                    <Option value={2}>2</Option>
                    <Option value={3}>3</Option>
                    <Option value={4}>4</Option>
                    <Option value={5}>5</Option>
                    <Option value={6}>6</Option>
                    <Option value={7}>7</Option>
                  </Select>
                }
              </Col>
            </Row>
            <Row className="form-row">
              <Col className="form-col" span={8}>
                <span className="lable">总工作时长：</span>
                <span>{this.state.editFlag ? this.state.workday*8 : this.state.record.totalHour}</span>
              </Col> 
              <Col className="form-col" span={8}>
                <span className="lable">有效输出时长：</span>
                <span>{this.state.editFlag ? `${this.state.timeUsed/(this.state.workday*8)*100}%` : this.state.record.effectRate}</span>
              </Col>
              <Col className="form-col" span={8}>
                <span className="lable">剩余时间占比：</span>
                <span>{this.state.editFlag ? `${(100 - this.state.timeUsed/(this.state.workday*8)*100)}%` : this.state.record.surplusRate}</span>
              </Col>
            </Row>
            <Row className="table">
              <Table columns={columns2} title={() => !this.state.editFlag ? '' : <a onClick={this.addData} className="add-data">添加数据</a>} dataSource={this.state.weeklyData}
                pagination={{defaultPageSize: 10, showSizeChanger: true}} />
            </Row>
            <Row className="table button-group">
              {
                !this.state.editFlag ? '' : <Button className="create-button" type="primary" onClick={this.submit} >提交</Button>
              }
              <Button className="create-button" type="primary" onClick={this.createBack}>返回</Button>
            </Row>
          </Card>
        </div>
        <Modal
          title={this.state.modifyRecord === '' ? '添加数据' : '修改数据'}
          width={980}
          wrapClassName="vertical-center-modal"
          visible={this.state.modalVisible}
          footer={null}
          closable={false}
        >
        {
          this.state.modalVisible ? 
          <WeeklyForm close={this.closeModal} submit={this.submitData} index={this.state.index} 
          modifyRecord={this.state.modifyRecord} projectInfo={this.state.projectInfo} projectCode={this.setProjectCode} ></WeeklyForm>
          : ""
        }
        </Modal>
      </section>
    )
  }
}
export default withRouter(PersonalWeekly);
